<?php
/**
 * Created by PhpStorm.
 * User: mac
 * Date: 2018/6/22
 * Time: 14:47
 */

namespace app\api\controller;


use app\admin\model\authRule;
use think\Request;

class Mem extends Api
{
    //获取用户个人资料
    public function getinfo(){
        $id = $this->cache['id'];
        if(!$id && !is_numeric($id)){
            return show(false,0,'token已失效,请刷新页面重新获取');
        }
        try{
            $user = model("Users")->getUsersById($id);
        }catch(\Exception $e){
            return show(false,0,$e->getMessage());
        }

        $data = array(
            'BirthdayDesc' => $user['birthday'],
            'CourseReadRuleName' => '',
            'Gender' => $user['gender'],
            'HeadImgDesc' => $user['image_url'],
            'InvUserCount' => '',
            'Phone' => '',
            'UserName' => $user['name'],
        );

        return show(true,0,'OK',$data);
    }


    //修改个人资料
    public function setinfo(){
        //获取当前用户ID
        $id = $this->cache['id'];
        if(!$id && !is_numeric($id)){
            return show(false,0,'token已失效,请刷新页面重新获取');
        }

        //获取传递过来的修改的数据
        $data = array(
            'image_url' => input('post.headimg'),
            'name' => input('post.username'),
            'birthday' => str_replace("-","/",input('post.birthday')),
        );

        //入库操作
        try{
            $res = model("Users")->UpdateUsersById($id,$data);
        }catch(\Exception $e){
            return show(false,0,$e->getMessage());
        }

        //返回数据

        return show(true,0,'修改成功');

    }


    //我的课程
    public function PayCourse(){
        //获取传递过来的页数
        $page = input('post.pageindex');

        //获取当前用户的ID
        $uid = $this->cache['id'];
        if(!$uid && !is_numeric($uid)){
            return show(false,0,'token已失效,请刷新页面重新获取');
        }

        try{
            //获取当前页数的数据
            $myCourse = model("MyCourse")->getMyCourseById($uid,$page);
            //获取当前课程的音频总数
            $count = model("MyCourse")->getMyCourseCountById($uid);
            //判断是否评论过
            $isEval = model("Comments")->getIsEvaluateById($uid);
        }catch(\Exception $e){
            return show(false,0,$e->getMessage());
        }


        $pageCon = count($myCourse);

        //拼接数据
        $result = array(
            'CurrentCount' => $pageCon,
            'IsNextPage' => false,
            'IsPreviousPage' => false,
            'Items' => self::GetItems($myCourse,$count,$isEval),
            'PageIndex' => $page,
            'PageSize' => $pageSize = 10,
            'TotalCount' => $count,
            'TotalPages' => '',
        );

        return show(true,0,'',$result);

    }


    //我的拼团
    public function GroupTask(){
        //获取当前用户ID
        $id = $this->cache['id'];
        if(!$id && !is_numeric($id)){
            return show(false,0,'token已失效,请刷新页面重新获取');
        }
        //获取传递过来的页数
        $page = input('post.pageindex');
        //获取前端传递过来的状态
        $status = input('post.state');
        //入库操作
        try{
            $group = model("Group")->getGroupByUserId($id,$page,10,$status);
        }catch(\Exception $e){
            return show(false,0,$e->getMessage());
        }

        //拼接数据
        $result = array(
            'CurrentCount' => count($group),
            'IsNextPage' =>'',
            'IsPreviousPage' => '',
            'Items' => self::getGroupItem($group),
            'PageIndex' => $page,
            'PageSize' => 10,
            'TotalCount' => 1,
            'TotalPages' => 1,
        );
        return show(true,0,'OK',$result);
    }


    //我的邀请
    public function share(){
        //获取当前用户的ID
        $id = $this->cache['id'];
        if(!$id && !is_numeric($id)){
            return show(false,0,'token已失效,请刷新页面重新获取');
        }
        //入库操作
        try{
            $user = model("Users")->getUsersById($id);
        }catch(\Exception $e){
            return show(false,0,$e->getMessage());
        }

        //转化时间
        $NowTime = time();
        $cha = $NowTime - $user['register_time'];
        $time = intval($cha / 86400);

        if(!$user['qr_code']){
            //请图片上传到自己服务器
            $qrcode = self::getQrCodeById($id);
            $res['qr_code'] = 'https://'.$_SERVER['HTTP_HOST'].'/uploads/code/'.$id.'.jpg';
            file_put_contents('./uploads/code/'.$id.'.jpg',$qrcode);

            try{
                model("Users")->UpdateUsersById($id,$res);
            }catch(\Exception $e){
                return show(false,0,$e->getMessage());
            }
        }


        //返回数据给前端
        $result= array(
            'Qrcode' => $res['qr_code'],
            'Title' => '我在[香蜜读书会]学习了'.$time.'天，诚邀你成为我的同学，一起学习一起进步',
        );
        return show(true,0,'OK',$result);
    }


    //我的赠送
    public function getGiveOrders(){
        //获取当前用户的ID
        $id = $this->cache['id'];
        if(!$id && !is_numeric($id)){
            return show(false,0,'token已失效,请刷新页面重新获取');
        }

        //获取当前页数
        $page = input('post.pageindex');

        //入库操作
        try{
            $giveOrder = model("GiveOrder")->getGiveOrderByUserId($id,$page);
        }catch(\Exception $e){
            return show(false,0,$e->getMessage());
        }

        //拼接数据
        $result = array(
            'CurrentCount' => count($giveOrder),
            'IsNextPage' => '',
            'IsPreviousPage' => '',
            'Items' => self::getGiveOrderItem($giveOrder),
            'PageIndex' => $page,
            'PageSize' => 10,
            'TotalCount' => '',
            'TotalPages' => '',
        );
        return show(true,0,'OK',$result);

    }

    //我的邀请记录
    public function inviters(){
        //获取当前用户ID
        $id = $this->cache['id'];
        //获取当前页数
        $page = input("post.pageindex");

        //入库操作
        try{
            $invites = model("Invite")->getInViteById($id,$page);
        }catch(\Exception $e){
            return show(false,0,$e->getMessage());
        }

        //拼接数据
        $result = array(
            'CurrentCount' => count($invites),
            'IsNextPage' => '',
            'IsPreviousPage' => '',
            'Items' => array(),
            'PageIndex' => $page,
            'PageSize' => 10,
            'TotalCount' => '',
            'TotalPages' => '',
        );
        return show(true,0,'Ok',$result);
    }


    //生成只是卡片
    public function gen1(){
        //获取用户ID
        $id = $this->cache['id'];

        $s = input('post.s');

        //获取课程ID
        $courseId = input("post.courseId") ? input('post.courseId') : input('post.courseid');

        try{
            //获取用户的邀请二维码
            $user = model("Users")->getUsersById($id);
            //获取课程海报背景图
            $background = model("WebConfig")->getgetgmxz();
            //根据课程ID获取课程信息
            $course = model("Courses")->getCourseById($courseId);
        }catch(\Exception $e){
            return show(false,0,$e->getMessage());
        }


        //判断有没有生成过二维码
        if(!$user['qr_code']){
            //请图片上传到自己服务器
            $qrcode = self::getQrCodeById($id);
            $res['qr_code'] = 'https://'.$_SERVER['HTTP_HOST'].'/uploads/code/'.$id.'.jpg';
            file_put_contents('./uploads/code/'.$id.'.jpg',$qrcode);

            try{
                model("Users")->UpdateUsersById($id,$res);
            }catch(\Exception $e){
                return show(false,0,$e->getMessage());
            }
        }

        if(!$s){ /****生成海报*****/


            //获取用户上传的图片路径
            $image = input('post.img');

            //生成海报
            $config = array(
                'text'=>array(
                    array(
                        'text'=> $user['name'],
                        'left'=>0,
                        'top'=>-195,
                        'fontPath'=>'./static/home/drcode/SIMHEI.TTF',     //字体文件
                        'fontSize'=>14,             //字号
                        'fontColor'=>'125,125,125',       //字体颜色
                        'angle'=>0,
                    )
                ),
                'image'=>array(
                    array(
                        'url'=>$user['image_url'],       //用户上传图片资源路径
                        'left'=>0,
                        'top'=>0,
                        'stream'=>0,
                        'right'=>0,
                        'bottom'=>0,
                        'width'=>550,
                        'height'=>469,
                        'opacity'=>100
                    ),
                    array(
                        'url'=>$user['qr_code'],   //二维码
                        'left'=>220,
                        'top'=>-260,
                        'right'=>0,
                        'stream'=>0,
                        'bottom'=>0,
                        'width'=>120,
                        'height'=>120,
                        'opacity'=>100
                    ),
                ),
                'background'=>$background['course_poster'],   //背景图片路径
            );

            //生成海报
            $result = self::createPoster($config,'./uploads/poster/course_'.$id.'.jpg');

            $res = 'https://'.$_SERVER['HTTP_HOST'].'/uploads/poster/course_'.$id.'.jpg';
        }else if($s == 1){
            /****生成知识卡片*****/
            $config = array(
                'text'=>array(
                    array(
                        'text'=>$user['name'].'的知识笔记',
                        'left'=>100,
                        'top'=>-890,
                        'fontPath'=>'./SIMHEI.TTF',     //字体文件
                        'fontSize'=>16,             //字号
                        'fontColor'=>'125,125,125',       //字体颜色
                        'angle'=>0,
                    ),
                    array(
                        'text'=>"《".$course['Title']."》     ".$course['AuthorName'],
                        'left'=>65,
                        'top'=>-365,
                        'fontPath'=>'./SIMHEI.TTF',     //字体文件
                        'fontSize'=>18,             //字号
                        'fontColor'=>'0,0,0',       //字体颜色
                        'angle'=>0,
                    )
                ),
                'image'=>array(
                    array(
                        'url'=>$user['image_url'],       //图片资源路径
                        'left'=>20,
                        'top'=>20,
                        'stream'=>0,             //图片资源是否是字符串图像流
                        'right'=>0,
                        'bottom'=>0,
                        'width'=>1,
                        'height'=>1,
                        'opacity'=>100
                    ),
                    array(
                        'url'=>$user['qr_code'],
                        'left'=>80,
                        'top'=>-93,
                        'right'=>0,
                        'stream'=>0,
                        'bottom'=>0,
                        'width'=>159,
                        'height'=>162,
                        'opacity'=>100
                    ),
                ),
                'background'=>$background['audio_poster'],
            );

            //生成海报
            $result = self::createPoster($config,'./uploads/poster/audio_'.$id.'.jpg');

            $res = 'https://'.$_SERVER['HTTP_HOST'].'/uploads/poster/audio_'.$id.'.jpg';

        }else if($s == 2){
            /****生成海报*****/
            $config = array(
                'text'=>array(
                    array(
                        'text'=>'a',
                        'left'=>0,
                        'top'=>0,
                        'fontPath'=>'./SIMHEI.TTF',     //字体文件
                        'fontSize'=>1,             //字号
                        'fontColor'=>'125,125,125',       //字体颜色
                        'angle'=>0,
                    ),
                ),
                'image'=>array(
                    array(
                        'url'=>$user['image_url'],       //图片资源路径
                        'left'=>20,
                        'top'=>20,
                        'stream'=>0,             //图片资源是否是字符串图像流
                        'right'=>0,
                        'bottom'=>0,
                        'width'=>100,
                        'height'=>100,
                        'opacity'=>100
                    ),
                    array(
                        'url'=>$user['qr_code'],
                        'left'=>36,
                        'top'=>-93,
                        'right'=>0,
                        'stream'=>0,
                        'bottom'=>0,
                        'width'=>159,
                        'height'=>158,
                        'opacity'=>100
                    ),
                ),
                'background'=>$course['Poster'],
            );

            //生成海报
            $result = self::createPoster($config,'./uploads/poster/poster_'.$id.'.jpg');

            $res = 'https://'.$_SERVER['HTTP_HOST'].'/uploads/poster/poster_'.$id.'.jpg';
        }

        if($result){
            return show(true,0,'',$res);
        }else{
            return show(false,0,'生成失败');
        }

    }


    public function addweixinmsgkey(){

    }



    //我的课程（立即评论）
    public function commentcheck(){
        //获取课程ID
        $courseId = input("post.CourseId");
        //入库操作
        try{
            $course = model("Courses")->getCoursesById($courseId);
        }catch(\Exception $e){
            return show(false,0,$e->getMessage());
        }

        //拼接数据
        $course['Code'] = 0;
        $course['Data'] = null;
        $course['Message'] = null;
        $course['Success'] = false;

        return show(true,0,'OK',$course);
    }

    //提交我的评论
    public function commentsave(){
        //获取当前用户ID
        $res['user_id'] = $this->cache['id'];
        //获取课程ID
        $res['course_id'] = input("post.CourseId");
        //获取评论内容
        $res['content'] = input('post.content');
        //评论状态
        $res['status'] = 1;
        //评论时间
        $res['comment_time'] = time();

        //入库添加操作
        try{
            $id = model("Comments")->getCommentAdd($res);
        }catch(\Exception $e){
            return show(false,0,$e->getMessage());
        }

        //判定是否添加成功
        if(!$id && !is_numeric($id)){
            return show(false,0,'添加失败');
        }
            return show(true,0,'ID='.$id.'的数据添加成功');

    }


    //分享海报
    public function getamount(){
        return show(true,0,'');
    }





    //我的课程数据Item拼接
    public static function getGiveOrderItem($items){
        if(!$items && !is_array($items)){
            return [];
        }
        $res = array();
        foreach($items as $k => $v){
            $res[$k]['CourseId'] = $v['course_id'];
            $res[$k]['GiveUserName'] = '';
            $res[$k]['Id'] = $v['id'];
            $res[$k]['IsGive'] = $v['give_user_id'] ? true : false;
            $res[$k]['Time'] = $v['give_time'];
            $res[$k]['Title'] = $v['title'];
        }
        return $res;

    }

    //我的拼团数据Item拼接
    public static function getGroupItem($data){
        if(!$data && !is_array($data)){
            return [];
        }

        $res = array();
        foreach($data as $k => $v){
            $res[$k]['AuthorDesc'] = '';
            $res[$k]['AuthorName'] = $v['name'];
            $res[$k]['BuyCount'] = $v['num']."已购买";
            $res[$k]['CourseIs'] = $v['CourseId'];
            $res[$k]['CourseName'] = $v['title'];
            $res[$k]['CreateTimeDesc'] = '';
            $res[$k]['GroupOrderId'] = $v['groupOrderId'];
            $res[$k]['GroupPrice'] = $v['g_price'];
            $res[$k]['Id'] = md5($v['id']);
            $res[$k]['ImageUrlDesc'] = $v['img_url'];
            $res[$k]['Price'] = $v['price'];
            $res[$k]['StateDesc'] = getGroupStatus($v['status']);
            $res[$k]['WhenLong'] = $v['whenlong'];
        }
        return $res;
    }








    //我的课程数据Item拼接
    public static function getItems($items,$count,$isEval){
        if(!$items && !is_array($items)){
            return [];
        }
        $res = array();
        foreach($items as $k => $v){
            $res[$k]['AudioCount'] = $count;
            $res[$k]['AuthorDesc'] = null;
            $res[$k]['AuthorName'] = $v['name'];
            $res[$k]['BrowseDesc'] = $v['browse'];
            $res[$k]['CourseId'] = $v['id'];
            $res[$k]['ImgUrlDesc'] = $v['img_url'];
            $res[$k]['IsEnable'] = false;
            $res[$k]['IsEvaluate'] = $isEval ? true : false;
            $res[$k]['Title'] = $v['title'];
            $res[$k]['VideoCount'] = 0;
        }
        return $res;
    }







}